package com.mf.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.mf.entity.bo.exportExcel.ExportExcelBo;
import com.mf.entity.vo.MergePropVo;
import com.mf.handler.CustomMergeStrategy;
import com.mf.handler.CustomWidthAndHeightRule;
import com.mf.result.Result;
import com.mf.utils.CallHttpUtils;
import com.mf.utils.ExportExcelUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @Author: lmf
 * @Create: 2024/6/25 14:59
 * Description:
 */
@RestController
@RequestMapping("/excel")
@Tag(name = "根据Http接口导出excel")
@Slf4j
public class EasyExcelHomeController {
    @Operation(summary = "导出表格信息")
    @PostMapping("export")
    @SneakyThrows
    public Result<Void> export(@RequestBody ExportExcelBo exportExcelBo, HttpServletResponse response) {
        Object httpData = CallHttpUtils.callHttp(exportExcelBo.getCallHttp());
        // 需要导出的数据
        List<List<Object>> exportList = ExportExcelUtils.setExportData(exportExcelBo,httpData);
        assert exportList != null;

        // 设置响应头
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/vnd.ms-excel");
        String fileName = URLEncoder.encode(exportExcelBo.getExportTitle(), StandardCharsets.UTF_8);
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ExcelTypeEnum.XLSX.getValue());
        ServletOutputStream outputStream = response.getOutputStream();

        // 获取动态标题
        List<List<String>> headList = ExportExcelUtils.getHeader(exportExcelBo);

        // 获取合并规则
        List<MergePropVo> mergeRule = ExportExcelUtils.getMergeRule(exportExcelBo,httpData);
        EasyExcel.write(outputStream)
                .sheet(exportExcelBo.getExportTitle())
                .head(headList)
                .registerWriteHandler(new CustomWidthAndHeightRule(exportExcelBo))
                .registerWriteHandler(new CustomMergeStrategy(mergeRule))
                .doWrite(exportList);

        return Result.success(null);
    }
}
